# --- building ---
FROM common/pyinstaller:py37-alpine AS builder

ARG APP_NAME="milangze-backend"
ARG APP_FILE="main.py"

RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
RUN apk add make gcc musl-dev libffi-dev openssl-dev python3-dev

ADD requirements.txt /data/
RUN pip3 --no-cache-dir install --upgrade -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host=pypi.tuna.tsinghua.edu.cn pip
RUN pip3 --no-cache-dir install -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host=pypi.tuna.tsinghua.edu.cn -r /data/requirements.txt
RUN pip3 --no-cache-dir install -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host=pypi.tuna.tsinghua.edu.cn PyInstaller

RUN mkdir -p /app/${APP_NAME}
WORKDIR /app/${APP_NAME}

COPY . ./

RUN pyinstaller --name=${APP_NAME} --clean --key $(openssl rand -base64 32) $APP_FILE \
    --hidden-import=charset_normalizer.md__mypyc \
    --hidden-import=pymysql \
    --hidden-import=pymssql \
    --hidden-import=sqlalchemy \
    --hidden-import=sqlalchemy.sql.default_comparator

RUN mv etc dist/${APP_NAME}/

# --- producting ---
FROM alpine:latest

ARG APP_NAME="milangze-backend"
ENV APP_NAME=${APP_NAME}

RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
RUN apk update --no-cache
RUN apk --no-cache add tzdata && \
    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone

WORKDIR /app/${APP_NAME}
COPY --from=builder /app/${APP_NAME}/dist/${APP_NAME} ./
RUN chmod +x /app/${APP_NAME}/${APP_NAME} && mkdir -p /app/${APP_NAME}/logs

RUN echo -e "#!bin/sh\n$@\n./${APP_NAME}\n" > /usr/local/bin/entrypoint.sh \
    && chmod +x /usr/local/bin/entrypoint.sh

ENTRYPOINT [ "sh", "/usr/local/bin/entrypoint.sh" ]